package Hash;

import java.util.Scanner;

public class HashTable {
    Integer[] h;
    int p;//hash函数除留余数法的p
    public HashTable(int m){
        h=new Integer[m];
        for (int i = 0; i < m; i++) {
            h[i]=null;
        }
        //确定p值
        for (p = m; p>1 ; p--) {
            int i;
            for ( i=2;i<=p/2;i++){
                if (p%i==0){
                    break;
                }
            }
            if (i>p/2){
                break;
            }
        }
    }
    public int hash(Integer key){
        return key%p;
    }
    public void createTable(int n){
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入n个元素");
        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();
            int addr=hash(x);
            if(h[addr]==null){
                h[addr]=x;
            }else {
                for (int di = 0; di < h.length; di++) {
                    int hi=(addr+di)%h.length;
                    if (h[hi]==null){
                        h[hi]=x;
                        System.out.println(h[hi]);
                        break;
                    }
                }
            }
        }
    }
    public int searchTable(Integer key){
        int addr = hash(key);
        if (h[addr]==null){
            return  -1;
        }else if(key.equals(h[addr])){
            return addr;
        }else {
            for (int di = 0; di <h.length; di++) {
                int hi=(addr+di)%h.length;
                if (h[hi]==null){
                    return -1;
                }else if(key.equals(h[hi])){
                    return hi;
                }
            }
        }
        return -1;
    }
    public void print(int i){
        System.out.println("h["+i+"]:"+h[i]);
    }
    public void displayTable(){
        for (int i = 0; i < h.length; i++) {
            print(i);
        }
    }
}
